package com.thunder.soft.common.util;

import android.app.Activity;

import java.util.Stack;

public class ActivityManagerUtils {
    private Stack<Activity> mStack;

    /**
     * 构造方法中初始化 mStack
     */
    private ActivityManagerUtils() {
        mStack = new Stack<>();
    }

    // 声明 activity 管理工具类
    private static volatile ActivityManagerUtils utils;

    /**
     * 单例模式初始化工具类
     *
     * @return 返回 activity 管理工具类
     */
    public static ActivityManagerUtils getInstance() {
        if (utils == null) {
            synchronized (ActivityManagerUtils.class) {
                if (utils == null) {
                    utils = new ActivityManagerUtils();
                }
            }
        }
        return utils;
    }

    /**
     * 把打开的 activity 添加到栈
     *
     * @param activity 当前的activity
     */
    public void push(Activity activity) {
        mStack.push(activity);
    }

    /**
     * 调用 onDestroy 时弹栈
     *
     * @return 返回当前弹出的 Activity
     */
    public Activity pop() {
        return mStack.pop();
    }

    /**
     * 移除栈顶Activity并finish
     */
    public void finish() {
        Activity activity = mStack.pop();
        if (activity != null) {
            activity.finish();
        }
    }

    /**
     * finish所有 Activity
     */
    public void clearActivity() {
        for (Activity next : mStack) {
            if (next != null) {
                next.finish();
            }
        }
    }

    /**
     * 获取当前栈顶 Activity
     *
     * @return 返回栈顶 Activity
     */
    public Activity getCurrentActivity() {
        return mStack.peek();
    }

}